home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / cpp_libs / brent_cc.lha / brent_cc / vfminbr.cc < prev    next >
C/C++ Source or Header  |  1993-08-08  |  1KB  |  65 lines

  1. // This may look like C code, but it is really -*- C++ -*-
  2. //
  3. //            Verify FMINBR routine
  4.  
  5.  
  6. #include "math_num.h"
  7. #include <ostream.h>
  8.  
  9. static int counter;            // Iteration counter
  10.  
  11.             // Run a test
  12. static void test
  13.   (const double a, const double b, double (*f)(double x), const char *msg)
  14. {
  15.   double minloc;
  16.   counter = 0;
  17.   cout << form("\nFor function %s\nthe minimum over [%g,%g] is found"
  18.            " to be at\t%.9e\n",msg,a,b,
  19.            (minloc=fminbr(a,b,f)) );
  20.   cout << form("Min function value found\t%.4e\nNo. of iterations\t\t%d\n",
  21.            (*f)(minloc), counter);
  22. }
  23.  
  24. double f1(const double x)        // Test from the Forsythe book
  25. {
  26.   counter++;
  27.   return (sqr(x)-2)*x - 5;
  28. }
  29.  
  30. double f2(const double x)        // Modified test 1
  31. {
  32.   counter++;
  33.   return sqr( (sqr(x)-2)*x - 5 );
  34. }
  35.  
  36. double f3(const double x)
  37. {
  38.   counter++;
  39.   return sqr( cos(x) - x ) - 2;
  40. }
  41.  
  42. double f4(const double x)
  43. {
  44.   counter++;
  45.   return sqr( sin(x) - x ) + 1;
  46. }
  47.  
  48.  
  49. main()
  50. {
  51.   cout << "\n\n" << _Minuses <<
  52.           "\n\t\tTesting the Brent's one-dimensional minimizer\n\n";
  53.  
  54.   test(0.0,1.0,f1,"x^3 - 2*x - 5");
  55.   cout << "Exact min is at\t\t0.81650\n";
  56.  
  57.   test(2.0,3.0,f2,"(x^3 - 2*x - 5)^2");
  58.   cout << "Exact root is \t\t2.0945514815\n";
  59.  
  60.   test(2.0,3.0,f3,"(cos(x)-x)^2 - 2");
  61.   test(-1.0,3.0,f3,"(cos(x)-x)^2 - 2");
  62.   test(-1.0,3.0,f4,"(sin(x)-x)^2 + 1");
  63. }
  64.  
  65.